package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import com.dao.ClassDao;
import com.dao.UserDao;
import com.google.gson.Gson;
import com.model.User;

@WebServlet("/upload")
public class UploadSerlvet extends HttpServlet {

	protected void doGet(HttpServletRequest request, 
			  HttpServletResponse response) 
  	throws IOException, ServletException
	{
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			try {
				List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
				for(int i=0; i<items.size(); ++i) {
					FileItem file = items.get(i);
					if(!file.isFormField()) {
						String fileName = file.getName();
						String path = request.getSession().getServletContext().getRealPath("upload/");
						File f = new File(path, fileName);
						file.write(f);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	protected void doPost(HttpServletRequest request, 
			  HttpServletResponse response) 
		  throws IOException, ServletException
	{
		doGet(request, response);
	}
}
